﻿using System.Collections.Generic;
using System.Linq;

namespace BuzzX8.Xmpp.StreamElements.Builders
{
    public class StreamFeaturesListBuilder : CompositeElementBuilder<StreamFeaturesList, StreamFeature>
    {
        private StreamFeature currentFeature;

        protected override IEnumerable<string> GetSupportedElementNames()
        {
            return new[] {"stream:features"};
        }

        protected override StreamFeaturesList CreateNewElement(string name)
        {
            if (name == "stream:features") return new StreamFeaturesList();
            throw new System.NotImplementedException();
        }

        protected override void AddAttributeToEmbeddedNode(string name, string value)
        {
            if (IsCurrentNodeSaslFeature(name, value))
            {
                currentFeature = new SaslFeature();
                return;
            }
            if (IsCurrentNodeSimpleFeature(name))
            {
                currentFeature = new StreamFeature(CurrentNodeName, value);
                RootElement.AddFeature(currentFeature);
            }
        }

        private bool IsCurrentNodeSaslFeature(string attributeName, string attributeValue)
        {
            return CurrentNodeName == "mechanisms" && attributeName == "xmlns" && attributeValue == XmppNamespaces.Sasl;
        }

        private bool IsCurrentNodeSimpleFeature(string attributeName)
        {
            return attributeName == "xmlns" && Depth == 1;
        }

        protected override void SetEmbeddedNodeValue(string nodeName, string value)
        {
            if (nodeName == "mechanism") ((SaslFeature)currentFeature).Mechanisms.Add(value);
        }

        public override void EndNode()
        {
            if (CurrentNodeName == "mechanisms") RootElement.AddFeature(currentFeature);
            if (IsCurrentNodeRequired()) currentFeature.Required = true;
            base.EndNode();
        }

        private bool IsCurrentNodeRequired()
        {
            return CurrentNodeName == "required" && Depth == 2;
        }
    }
}
